package com.sangcomz.fishbun.ui.album.ui.slice;

import com.sangcomz.fishbun.BaseAbilitySlice;
import com.sangcomz.fishbun.FishBun;
import com.sangcomz.fishbun.Fishton;
import com.sangcomz.fishbun.ResourceTable;
import com.sangcomz.fishbun.adapter.image.ImageAdapter;
import com.sangcomz.fishbun.datasource.CameraDataSourceImpl;
import com.sangcomz.fishbun.datasource.FishBunDataSourceImpl;
import com.sangcomz.fishbun.datasource.ImageDataSourceImpl;
import com.sangcomz.fishbun.ui.album.AlbumContract;
import com.sangcomz.fishbun.ui.album.adapter.AlbumListAdapter;
import com.sangcomz.fishbun.ui.album.listener.AlbumClickListener;
import com.sangcomz.fishbun.ui.album.model.Album;
import com.sangcomz.fishbun.ui.album.model.AlbumMenuViewData;
import com.sangcomz.fishbun.ui.album.model.AlbumViewData;
import com.sangcomz.fishbun.ui.album.model.repository.AlbumRepositoryImpl;
import com.sangcomz.fishbun.ui.album.mvp.AlbumPresenter;
import com.sangcomz.fishbun.ui.picker.PickerActivity;
import com.sangcomz.fishbun.util.*;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.event.commonevent.*;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AlbumAbilitySlice extends BaseAbilitySlice implements AlbumContract.View, AlbumClickListener {

    private AlbumContract.Presenter albumPresenter;
    private DirectionalLayout groupEmptyView;
    private ListContainer recyclerAlbumList;
    private AlbumListAdapter adapter;
    private Text txtAlbumMessage;
    private CommonToolbar toolbar;
    private BaseGridSliceProvider.GridConfig horizontalConfig = new BaseGridSliceProvider.GridConfig();
    private BaseGridSliceProvider.GridConfig verticalConfig = new BaseGridSliceProvider.GridConfig();
    private PermissionEventSubscriber mSubscriber;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_album);
        try {
            albumPresenter = new AlbumPresenter(
                    this,
                    new AlbumRepositoryImpl(
                            new ImageDataSourceImpl(DataAbilityHelper.creator(AlbumAbilitySlice.this)),
                            new FishBunDataSourceImpl(Fishton.getInstance()),
                            new CameraDataSourceImpl(this)
                    ),
                    new MainUiHandler()
            );
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

        initView();
        albumPresenter.getDesignViewData();
        if (checkPermission()) albumPresenter.loadAlbumList();

        //订阅事件
        MatchingSkills skills = new MatchingSkills();
        skills.addEvent(PERMISSION_CALLBACK);
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(skills);
        mSubscriber = new PermissionEventSubscriber(subscribeInfo);
        try {
            CommonEventManager.subscribeCommonEvent(mSubscriber);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void initView() {

        groupEmptyView = (DirectionalLayout) findComponentById(ResourceTable.Id_group_album_empty);
        recyclerAlbumList = (ListContainer) findComponentById(ResourceTable.Id_recycler_album_list);
        txtAlbumMessage = (Text) findComponentById(ResourceTable.Id_txt_album_msg);

        findComponentById(ResourceTable.Id_iv_album_camera).setClickedListener(component -> albumPresenter.takePicture());

        verticalConfig.setPadding(1);
        verticalConfig.setItemHeight(68);

        horizontalConfig.setPadding(1);
//        horizontalConfig.setIndexCount(2);
        horizontalConfig.setItemHeight(68);
    }

    @Override
    public void onActive() {
        super.onActive();
        albumPresenter.onResume();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void showAlbumList(List<Album> albumList, ImageAdapter imageAdapter, AlbumViewData albumViewData) {
        recyclerAlbumList.setVisibility(Component.VISIBLE);
        groupEmptyView.setVisibility(Component.HIDE);
        setAlbumListAdapter(albumList, imageAdapter, albumViewData);
    }

    private void setAlbumListAdapter(List<Album> albumList, ImageAdapter imageAdapter, AlbumViewData albumViewData) {
        if (adapter == null) {
            verticalConfig.setIndexCount(albumViewData.getAlbumPortraitSpanCount());
            horizontalConfig.setIndexCount(albumViewData.getAlbumLandscapeSpanCount());
            adapter = new AlbumListAdapter(this, this, albumViewData.getAlbumThumbnailSize(), imageAdapter, verticalConfig);
            recyclerAlbumList.setItemProvider(adapter);
        }
        adapter.setAlbumList(albumList);
    }

    @Override
    public void showEmptyView() {
        groupEmptyView.setVisibility(Component.VISIBLE);
        recyclerAlbumList.setVisibility(Component.INVISIBLE);
        try {
            String msg = getResourceManager().getElement(ResourceTable.String_msg_no_image).getString();
            txtAlbumMessage.setText(msg);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setRecyclerViewSpanCount(AlbumViewData albumViewData) {
        if (adapter == null) return;

        if (getDisplayOrientation() == AbilityInfo.DisplayOrientation.LANDSCAPE.ordinal()) {
            horizontalConfig.setIndexCount(albumViewData.getAlbumLandscapeSpanCount());
            adapter.setLayoutConfig(horizontalConfig);
        } else {
            verticalConfig.setIndexCount(albumViewData.getAlbumPortraitSpanCount());
            adapter.setLayoutConfig(verticalConfig);
        }
    }

    @Override
    public void setRecyclerView(AlbumViewData albumViewData) {
        if (adapter == null) return;
        if (getDisplayOrientation() == AbilityInfo.DisplayOrientation.LANDSCAPE.ordinal()) {
            horizontalConfig.setIndexCount(albumViewData.getAlbumLandscapeSpanCount());
            adapter.setLayoutConfig(horizontalConfig);
        } else {
            verticalConfig.setIndexCount(albumViewData.getAlbumPortraitSpanCount());
            adapter.setLayoutConfig(verticalConfig);
        }
    }

    @Override
    public void setToolBar(AlbumViewData albumViewData) {
        toolbar = (CommonToolbar) findComponentById(ResourceTable.Id_abl_album_appbar);
        try {
            String msg = getResourceManager().getElement(ResourceTable.String_msg_loading_image).getString();
            if (txtAlbumMessage != null) txtAlbumMessage.setText(msg);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
//        ShapeElement background = new ShapeElement();
//        background.setRgbColor(new RgbColor());
        toolbar.setBackgroundColor(albumViewData.getColorActionBar());
        toolbar.tvTitle.setTextColor(new Color(albumViewData.getColorActionBarTitle()));
        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(albumViewData.getColorStatusBar());

        if (albumViewData.getDrawableHomeAsUpIndicator() != null) {
            toolbar.setImgBack(albumViewData.getDrawableHomeAsUpIndicator());
        }

        toolbar.tvTitle.setText(albumViewData.getTitleActionBar());
        toolbar.btnBack.setVisibility(Component.VISIBLE);

        //todo 设置系统状态栏的字体是亮体还是暗体
//        if (albumViewData.isStatusBarLight()) {
//            toolbar.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
//        }

        toolbar.btnBack.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminateAbility();
            }
        });

        onCreateOptionsMenu();

        onOptionsItemSelected(toolbar.btnSelect);
        onOptionsItemSelected(toolbar.btnSelectTitle);
    }

    public boolean onCreateOptionsMenu() {

        albumPresenter.getAlbumMenuViewData(new AlbumContract.Presenter.CallBack() {
            @Override
            public void Call(AlbumMenuViewData data) {

                if (data.getHasButtonInAlbumActivity()) {
                    toolbar.hideAllSelectBtn();
                    if (data.getDrawableDoneButton() != null) {
                        toolbar.setImgSelect(data.getDrawableDoneButton());
                        toolbar.imgSelect.setVisibility(Component.VISIBLE);
                    } else if (data.getStrDoneMenu() != null) {
                        toolbar.setBtnSelectTitle(data.getStrDoneMenu(), data.getColorTextMenu());
                    }
                }
            }
        });

        return true;
    }

    private void onOptionsItemSelected(Component item) {
        item.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (item.getId() == ResourceTable.Id_btn_select || item.getId() == ResourceTable.Id_btn_select_title) {
                    albumPresenter.onClickMenuDone();
                }
            }
        });

    }

    @Override
    public void changeToolbarTitle(int selectedImageCount, AlbumViewData albumViewData) {
        if (toolbar != null) {
            String title = "";
            if (albumViewData.getMaxCount() == 1 || !albumViewData.isShowCount()) {
                title = albumViewData.getTitleActionBar();
            } else {
                try {
                    title = getResourceManager().getElement(ResourceTable.String_title_toolbar)
                            .getString(albumViewData.getTitleActionBar(), selectedImageCount, albumViewData.getMaxCount());
                } catch (IOException | NotExistException | WrongTypeException e) {
                    e.printStackTrace();
                }
            }
            toolbar.tvTitle.setText(title);
        }

    }

    @Override
    public void finishActivityWithResult(List<Uri> selectedImages) {
        Intent intent = new Intent();
        intent.setSequenceableArrayListParam(FishBun.INTENT_PATH, new ArrayList<>(selectedImages));
        getAbility().setResult(RESULT_OK, intent);
        terminateAbility();
    }

    @Override
    public void refreshAlbumItem(int position, ArrayList<Uri> imagePath) {
        String thumbnailPath = imagePath.get(imagePath.size() - 1).toString();
        int addedCount = imagePath.size();
        if (adapter != null) {
//            adapter.updateAlbumMeta(0, addedCount, thumbnailPath);
            adapter.updateAlbumMeta(position, addedCount, thumbnailPath);
        }
    }

    @Override
    public void scanAndRefresh() {
        if (cameraUtil.savedPath.isEmpty()) return;

        new SingleMediaScanner(this, new File(cameraUtil.savedPath), () -> albumPresenter.loadAlbumList());
    }

    @Override
    public void showNothingSelectedMessage(String nothingSelectedMessage) {
//        getUITaskDispatcher().syncDispatch(() -> new ToastDialog(AlbumAbilitySlice.this).setText(nothingSelectedMessage).show());
        ToastUtil.showToast(getContext(), nothingSelectedMessage);
    }

    @Override
    public void showMinimumImageMessage(int currentSelectedCount) {
        try {
            String msg = getResourceManager().getElement(ResourceTable.String_msg_minimum_image).getString(currentSelectedCount);
//            new ToastDialog(AlbumAbilitySlice.this).setText(msg).show();
            ToastUtil.showToast(getContext(), msg);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void takePicture(String saveDir) {
        if (checkCameraPermission()) {
            cameraUtil.takePicture(AlbumAbilitySlice.this, saveDir, TAKE_A_PICTURE_REQUEST_CODE);
        }
    }

    @Override
    public void saveImage() {
        if (cameraUtil.savedPath.isEmpty()) return;

        cameraUtil.saveImage(DataAbilityHelper.creator(this), new File(cameraUtil.savedPath));
    }

    @Override
    public void onAlbumClick(int position, Album album) {
        Intent intent = PickerActivity.getPickerActivityIntent(this, album.getId(), album.getDisplayName(), position);
        startAbilityForResult(intent, ENTER_ALBUM_REQUEST_CODE);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        switch (requestCode) {
            case ENTER_ALBUM_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    albumPresenter.finish();
                } else if (resultCode == TAKE_A_NEW_PICTURE_RESULT_CODE) {
                    albumPresenter.loadAlbumList();
                }
                break;
            case TAKE_A_PICTURE_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    albumPresenter.onSuccessTakePicture();
                } else {
                    if (!cameraUtil.savedPath.isEmpty()) {
                        new File(cameraUtil.savedPath).delete();
                    }
                }
                break;
        }
    }

    private boolean checkPermission() {
        return permissionCheck.checkStoragePermission(PERMISSION_STORAGE);
    }

    private boolean checkCameraPermission() {
        return permissionCheck.checkCameraPermission(PERMISSION_CAMERA);
    }

    @Override
    protected void onStop() {
        super.onStop();
        albumPresenter.release();
        try {
            CommonEventManager.unsubscribeCommonEvent(mSubscriber);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    class PermissionEventSubscriber extends CommonEventSubscriber {

        public PermissionEventSubscriber(CommonEventSubscribeInfo info) {
            super(info);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            Intent intent = commonEventData.getIntent();
            if (intent.getAction().equals(PERMISSION_CALLBACK)) {
                int requestCode = intent.getIntParam(REQUEST_CODE, -1);
                if (requestCode == PERMISSION_STORAGE) {
                    int[] grants = intent.getIntArrayParam(GRANT_RESULTS);
                    if (grants[0] == 0 && checkPermission()){
                        albumPresenter.loadAlbumList();
                    }
                }
            }
        }
    }
}
